package com.testmodelconnectionapp;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

/**
 * Created by 张英杰 on 2018/6/1.
 */

public class HandlerService extends Service {

    public static final int Handler_ActivityMSG = 0x00;
    public static final int Handler_Start = 0x01;
    public static final int Handler_End = 0x02;
    public static final int Handler_SendToAidlActivityMsg = 0x07;
    private static final String TAG = "HandlerService";

    private Messenger activitMessenger;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Handler_ActivityMSG:
                    activitMessenger = msg.replyTo;
                    break;
                case Handler_Start:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);
                                Message obtain = Message.obtain();
                                obtain.what=Handler_SendToAidlActivityMsg;
                                obtain.obj="service 接收到消息 并 开始";
                                try {
                                    if (activitMessenger != null) {
                                        activitMessenger.send(obtain);
                                    }
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    Log.i(TAG, "handleMessage: ssss");
                    break;
                case Handler_End:
                    Log.i(TAG, "handleMessage: EEEE");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        Messenger message = new Messenger(mHandler);
        return message.getBinder();
    }
}
